package com.yan.gulimall.auth.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yan.common.constant.AuthServerConstant;
import com.yan.common.utils.HttpUtils;
import com.yan.common.utils.R;
import com.yan.common.vo.MemberResponseVo;
import com.yan.gulimall.auth.feign.MemberFeignService;
import com.yan.gulimall.auth.vo.SocialUserVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth/weibo/success")
    public String weiboLogin(@RequestParam("code") String code, HttpSession session) throws Exception {

        // 根据Oauth2.0协议,api交互必须携带三方登录的code码,用来交互三方的令牌accessToken
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "微博api账号");
        map.put("client_secret", "微博api的secret");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://gulimall.com/oauth/weibo/success");
        map.put("code", code);
        HttpResponse response = HttpUtils.doPost("api.weibo.com", "/oauth2/access_token", "post", null, null, map);

        // 判断是否返回code成功
        if (response.getStatusLine().getStatusCode() == 200) {
            // 获取到了accessToken
            String json = EntityUtils.toString(response.getEntity());
            SocialUserVo socialUserVo = JSON.parseObject(json, SocialUserVo.class);

            // 如果该用户未登录过,则通过socialUserVo来进行注册Gulimall
            // 远程调用member服务,判断是进行登录还是注册操作
            R r = memberFeignService.oauthLogin(socialUserVo);
            if (r.getCode() == 0) {
                MemberResponseVo data = r.getData("data", new TypeReference<MemberResponseVo>() {
                });
                session.setAttribute(AuthServerConstant.LOGIN_USER,data);
                return "redirect:http://gulimall.com";
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }

        } else {
            // 未成功登录三方账号,返回登录页
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
